package com.jds.test.proto.rsa;

import com.jds.test.proto.MyBaseProtoV2;
import com.jds.test.proto.ServerHandler4V2Heart;
import com.jds.test.proto.ServerHeartbeatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * 两端SimpleChannelInboundHandler＋Object编解码（LengthFieldBasedFrameDecoder）
 * Created by sunyuming on 18/8/1.
 */
public class Server4 {
    public static void main(String[] args)  {

        //boss线程监听端口，worker线程负责数据读写
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try{
            //辅助启动类
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置线程池
            bootstrap.group(boss,worker);

            //设置socket工厂
            bootstrap.channel(NioServerSocketChannel.class);

            //设置管道工厂
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //获取管道
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(10000, 0, 4, 0, 4));
                    pipeline.addLast(new MyProtobufServerDecoder());
                    pipeline.addLast(new ProtobufDecoder(MyBaseProtoV2.BaseProto.getDefaultInstance()));
                    pipeline.addLast(new LengthFieldPrepender(4));
                    pipeline.addLast(new MyProtobufServerEncoder());
                    pipeline.addLast(new ProtobufEncoder());

                    pipeline.addLast(new IdleStateHandler(61, 0, 0, TimeUnit.SECONDS));
                    pipeline.addLast(new ServerHeartbeatHandler());
                    //处理类
                    pipeline.addLast(new ServerHandler4V2Heart());
                }
            });

            //绑定端口
            ChannelFuture future = bootstrap.bind(8866).sync();
            System.out.println("server start ...... ");

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅退出，释放线程池资源
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
